optbuilder: preserve ORDER BY in set-returning UDFs with OUT parameters #158162
+62
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Fixes #144013
When set-returning UDFs with OUT parameters are called directly in a SELECT list (e.g.,
SELECT f()), CockroachDB wraps multiple result columns into a single tuple column. During this transformation, two functions created new scopes without preserving ordering information, causing ORDER BY clauses in the UDF body to be ignored.Solution
This PR fixes the issue by calling
copyOrdering()in two places inpkg/sql/opt/optbuilder/routine.go:combineRoutineColsIntoTuple- preserves ordering when wrapping columns into a tuplemaybeAddRoutineAssignmentCasts- preserves ordering when adding type castsThe
copyOrdering()method not only copies the ordering metadata but also adds the columns referenced by the ordering toextraCols, ensuring they remain available for the optimizer to enforce the ordering.Testing
Added a new regression test
out_params_orderinginpkg/sql/logictest/testdata/logic_test/udf_setofthat verifies ORDER BY is preserved for both ascending and descending order with OUT parameters.Release note
Release note (bug fix): Fixed a bug where ORDER BY clauses in set-returning SQL user-defined functions with OUT parameters were ignored when the function was called directly in a SELECT list (e.g., SELECT f()). The ordering is now properly preserved and enforced.